
package cs342.uwosh.edu.MyWorldApp;
import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.PopupMenu;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

import cs342.uwosh.edu.R;
import cs342.uwosh.edu.MyWorldApp.misc.UserReciever;
import cs342.uwosh.edu.MyWorldApp.cloud.CloudLinker;
import cs342.uwosh.edu.MyWorldApp.misc.AsyncMethod;
import cs342.uwosh.edu.MyWorldApp.storage.User;
import android.location.Location;



public class MyWorldAppActivity extends MapActivity implements LocationListener {
	
	private UserReciever receiver;
	
	private MapView mapView;
	private double latitudeE6 = 44.021304;
	private double longitudeE6 = -88.55079;
	String[][] friends; //REPLACE ME WITH SQL INFO
	GeoPoint point;
	String add;
	Geocoder geoCoder;
	List<Address> addresses;
	OverlayItem overlayitem;
	private User currentUser;
	private Location focus;
	private LocationManager locationManager;
	private String provider;
	Criteria criteria;
	android.location.Location location;
	MapController mapController;
	CustomItemizedOverlay itemizedOverlay;
	List<Overlay> mapOverlays;
	GeoPoint updatedYou;
	
	
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
    	Intent myIntent = getIntent();
		currentUser = myIntent.getParcelableExtra("user");
		focus = (Location)myIntent.getParcelableExtra("focus");
        
		
        mapView = (MapView) findViewById(R.id.mapView);       
        mapView.setBuiltInZoomControls(true);
        
        
		// Get the location manager
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		// Define the criteria how to select the locatioin provider -> use
		// default
		criteria = new Criteria();
		provider = locationManager.getBestProvider(criteria, false);
		location = locationManager.getLastKnownLocation(provider);

		// Initialize the location fields
		if (location != null) {
			System.out.println("Provider " + provider + " has been selected.");
			latitudeE6 = (int) (location.getLatitude());
			longitudeE6 = (int) (location.getLongitude());
		}
		else
		{
			Toast.makeText(getBaseContext(), "Please update your location using DDMS", Toast.LENGTH_SHORT).show();
		}
		
			friends = currentUser.getFriendsLocations();
      
        
        mapOverlays = mapView.getOverlays();
        //Icon of marker
        Drawable drawable = this.getResources().getDrawable(R.drawable.marker);
		itemizedOverlay = new CustomItemizedOverlay(drawable, this);
		
		//Creates multiple friends markers from the string array
		for(int i = 0; i<friends.length; i++)
		{
	        double lat = Double.parseDouble(friends[i][0]);
	        double lng = Double.parseDouble(friends[i][1]);
	        point = new GeoPoint(
		            (int) (lat * 1E6), 
		            (int) (lng * 1E6));
	        geoCoder = new Geocoder( getBaseContext(), Locale.getDefault());
	        
	        try {
		        addresses = geoCoder.getFromLocation(lat, lng, 1);
		        add = "";
	            if (addresses.size() > 0) 
	            {
	                for (int j=0; j<addresses.get(0).getMaxAddressLineIndex(); j++)
	                   add += addresses.get(0).getAddressLine(j) + "\n";
	            }
	            
	        } 
	        catch (IOException e) {                
                e.printStackTrace();
            }   
		        
			overlayitem = new OverlayItem(point, "Friend " + friends[i][2] + " is located @", add);
			
			itemizedOverlay.addOverlay(overlayitem);
			mapOverlays.add(itemizedOverlay);
	         
		}
		
		//Sets YOUR location on map
		GeoPoint you = new GeoPoint((int) (latitudeE6 * 1E6), (int) (longitudeE6 * 1E6));
		overlayitem = new OverlayItem(you, "YOU ARE", "HERE");
		itemizedOverlay.addOverlay(overlayitem);
		mapOverlays.add(itemizedOverlay);
		mapController = mapView.getController();
		mapController.animateTo(you);
		mapController.setZoom(10);
		
		// mapView.invalidate();
		
    }

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
	
	

	
	/* Request updates at startup */
	@Override
	protected void onResume() {
		//currentUser = receiver.getResultExtras(true).getParcelable("user");
		locationManager.requestLocationUpdates(provider, 400, 1, this);
		super.onResume();
		
		//Creates multiple friends markers from the string array
				for(int i = 0; i<friends.length; i++)
				{
			        double lat = Double.parseDouble(friends[i][0]);
			        double lng = Double.parseDouble(friends[i][1]);
			        point = new GeoPoint(
				            (int) (lat * 1E6), 
				            (int) (lng * 1E6));
			        geoCoder = new Geocoder( getBaseContext(), Locale.getDefault());
			        
			        try {
				        addresses = geoCoder.getFromLocation(lat, lng, 1);
				        add = "";
			            if (addresses.size() > 0) 
			            {
			                for (int j=0; j<addresses.get(0).getMaxAddressLineIndex(); j++)
			                   add += addresses.get(0).getAddressLine(j) + "\n";
			            }
			            
			        } 
			        catch (IOException e) {                
		                e.printStackTrace();
		            }   
				        
					overlayitem = new OverlayItem(point, "Friend " + friends[i][2] + " is located @", add);
					
					itemizedOverlay.addOverlay(overlayitem);
					mapOverlays.add(itemizedOverlay);
			         
				}
	}

	/* Remove the locationlistener updates when Activity is paused */
	@Override
	protected void onPause() {
		super.onPause();
		locationManager.removeUpdates(this);
	}
	
	/* clears map */
	public void clearMap ()
	{
		if(!mapOverlays.isEmpty()) 
	     { 
	     mapOverlays.clear(); 
	     mapView.invalidate();

	 }
	}


	public void onLocationChanged(Location location) {
		clearMap();

		//UPDATE FRIENDS
		for(int i = 0; i<friends.length; i++)
		{
	        double lat = Double.parseDouble(friends[i][0]);
	        double lng = Double.parseDouble(friends[i][1]);
	        point = new GeoPoint(
		            (int) (lat * 1E6), 
		            (int) (lng * 1E6));
	        geoCoder = new Geocoder( getBaseContext(), Locale.getDefault());
	        
	        try {
		        addresses = geoCoder.getFromLocation(lat, lng, 1);
		        add = "";
	            if (addresses.size() > 0) 
	            {
	                for (int j=0; j<addresses.get(0).getMaxAddressLineIndex(); j++)
	                   add += addresses.get(0).getAddressLine(j) + "\n";
	            }
	            
		        } 
		        catch (IOException e) {                
	                e.printStackTrace();
	            }  
			overlayitem = new OverlayItem(point, "Friend nameHere is located @", add);
			
			itemizedOverlay.addOverlay(overlayitem);
			mapOverlays.add(itemizedOverlay);
	         
		}
		
	
		latitudeE6 = (location.getLatitude());
		longitudeE6 = (location.getLongitude());
		Toast.makeText(getBaseContext(), "Location Updated", Toast.LENGTH_SHORT).show();
		updatedYou = new GeoPoint((int) (latitudeE6 * 1E6), (int) (longitudeE6 * 1E6));
		overlayitem = new OverlayItem(updatedYou, "YOU ARE", "HERE");
		itemizedOverlay.addOverlay(overlayitem);
		mapOverlays.add(itemizedOverlay);
		mapController.animateTo(updatedYou);
		String cloudlocation = latitudeE6 + "/" + longitudeE6;
		CloudLinker l = new CloudLinker(getBaseContext());
		AsyncMethod<CloudLinker> a = new AsyncMethod<CloudLinker>(CloudLinker.class, l, "sendLocation");
		a.execute(currentUser.getUserName(), cloudlocation);
		
		
	}


	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}


	public void onProviderEnabled(String provider) {
		Toast.makeText(this, "Enabled new provider " + provider,
				Toast.LENGTH_SHORT).show();

	}


	public void onProviderDisabled(String provider) {
		Toast.makeText(this, "Disabled provider " + provider,
				Toast.LENGTH_SHORT).show();
	}
	public boolean onCreateOptionsMenu(Menu menu) {
    	super.onCreateOptionsMenu(menu);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.map_menu, menu);
        return true;
    }
    
	public boolean onOptionsItemSelected(MenuItem item) {
	     // Handle item selection
		Intent myIntent;
		switch (item.getItemId()) {
	    	 case R.id.friendsMenu:
	    		myIntent = new Intent(this,FriendsListActivity.class);
	    		myIntent.putExtra("user", currentUser);
	    		startActivity(myIntent);
	    		break;
		    case R.id.placesMenu:
				currentUser.setSearchingPlaces(!currentUser.isSearchingPlaces());
				
				//break;
		    case R.id.optionsMenu:
		    	myIntent = new Intent(this,OptionsActivity.class);
	    		myIntent.putExtra("user", currentUser);
	    		startActivityForResult(myIntent, OptionsActivity.UPDATE_USER_SETTINGS);
				break;
		    case R.id.logOutMenu:
		    	// Log in Activity
		    	logOut();
		    	break;
		    case R.id.exitMenu:
		    	super.onBackPressed();
		    	break;
		}
		return true;
	}
    
    public void logOut() {
    	Intent myIntent = new Intent(this,LogInActivity.class);
    	startActivity(myIntent);
    	finish();
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent newIntent) {
    	if(requestCode == OptionsActivity.UPDATE_USER_SETTINGS &&
    			resultCode == OptionsActivity.UPDATED_USER_SETTINGS) {
    		currentUser = newIntent.getParcelableExtra("user");
    		
    	}
    }
}